package com.evil.kingdom.interceptor;

import com.alibaba.fastjson.JSON;
import com.evil.kingdom.pojo.entity.token.SocketInfo;
import com.evil.kingdom.utils.TokenUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;
import java.util.Optional;

/**
 * @author liyang
 * @date 2024-05-18 13:58
 */
@Slf4j
@AllArgsConstructor
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    private final TokenUtil tokenUtil;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 获取token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        log.info("HandshakeInterceptor|token:{}", token);
        if (StringUtils.isBlank(token)) {
            return false;
        }
        // 验证token
        boolean tokenPresent = tokenUtil.isExistTokenInfo(token).isPresent();
        log.info("HandshakeInterceptor|token:{}, tokenPresent:{}", token, tokenPresent);
        if (!tokenPresent) {
            return false;
        }
        String hostAddress = request.getRemoteAddress().getAddress().getHostAddress();
        log.info("HandshakeInterceptor|hostAddress:{}", hostAddress);
        if (StringUtils.isBlank(hostAddress)) {
            return true;
        }
        Optional<SocketInfo> ipPresent = tokenUtil.isExistSocket(token);
        log.info("HandshakeInterceptor|token:{}, ipPresent:{}", token, JSON.toJSONString(ipPresent));
        if (ipPresent.isEmpty()) {
            return true;
        }
        SocketInfo socketInfo = ipPresent.get();
        return socketInfo.getIp().equals(hostAddress);
    }

}
